﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using System.Configuration;
using ueEngine.Framework.Common;

namespace DataPump
{
    public abstract class IResource
    {
        public int total, recrod, jumpwitherror,jumpwithtime,jumpwithempty,jumpwithganji, repeat;
        protected string[] Forbiddens = null;
        protected string ConnectStr = "";
        protected Dictionary<int, string> dict = new Dictionary<int, string>();
        public IResource(string constr)
        {
            SetDict();
            string forbiddens = "赶集@";
            if (!String.IsNullOrEmpty(forbiddens))
            {
                Forbiddens = forbiddens.Split('@');
            }
            else
            {
                throw new Exception("forbiddens配置节为空");
            }
            this.ConnectStr = constr;
        }
        protected string Pickbody(string html)
        {
            string body = new Regex("\\<body.*?\\>.*?\\</body\\>").Match(html).Value;
            return body;
        }
        private decimal GetMinSalary(string salary)
        {
            if (salary.Trim() == "面议" || String.IsNullOrEmpty(salary.Trim()))
            {
                return 0;
            }
            else
            {
                string s = new Regex("\\d+").Match(salary).Value;
                decimal res = 0;
                if (decimal.TryParse(s, out res))
                {
                    return res;
                }
                return 0;
            }
        }
        private decimal GetMaxSalary(string salary)
        {
            return 0;
        }
        private decimal GetSalaryPeriod(string salary)
        {
            if (salary.Contains("小时"))
            {
                return 160;
            }
            if (salary.Contains("天"))
            {
                return 40;
            }
            else if (salary.Contains("周"))
            {
                return 8;
            }
            else // (salary.Contains("月"))
            {
                return 1;
            }
        }
        public abstract void Do();
        protected abstract void SetDict();
        protected abstract void Analysts(string html, string uri, ref int count);
        protected abstract int PositionTypeMapping(string uri);
        protected abstract string PositionNameMapping(string uri);
        public abstract int WorkAreaMapping(string str);
        protected abstract int CompanyBusinessMapping(string orgstr);
        protected abstract int CompanyTypeMapping(string orgstr);
        protected abstract int CompanydimensionsMapping(string orgstr);
        protected abstract int GenderMapping(string gender);
        protected abstract int DegreeMapping(string degree);
        protected abstract int VacancyMapping(string vacancy);
        protected abstract int ExperiencedMapping(string experience);

        //protected void PostData(ref int count, List<Info> data)
        //{
        //    string agent = Common.GetRecruiter();
        //    foreach (var item in data)
        //    {
        //        using (SqlConnection con = new SqlConnection(ConnectStr))
        //        {
        //            con.Open();
        //            SqlTransaction tran = con.BeginTransaction();
        //            SqlCommand com = con.CreateCommand();
        //            com.Transaction = tran;
        //            try
        //            {
        //                int depositCompanyId = PostNewDepositCompany(com, agent, item.CompanyName, item.CopAbout, item.CopBusiness, item.CopType, item.CopDimensions);
        //                int recruitId = PostNewRecruitSheet(com, item.Caption, agent, depositCompanyId, 1, item.ContactMan, item.ContactPhone, item.Address);
        //                PostNewPosition(com, recruitId, item.PositionName, item.Vacancy, item.PositionType, item.Salry, "不限", item.Degree, item.Experience, item.PositionDescript);
        //                tran.Commit();
        //                com.Dispose();
        //            }
        //            catch (Exception e)
        //            {
        //                tran.Rollback();
        //                Console.WriteLine("添加第" + --count + "条数据异常");
        //                using (System.IO.StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "postdata.txt"))
        //                {
        //                    sw.WriteLine(e.ToString());
        //                }
        //            }
        //        }
        //    }
        //}
        protected int PostData(Info item)
        {
            string agent = Common.GetRecruiter();

            try
            {
                using (SqlConnection con = new SqlConnection(ConnectStr))
                {
                    con.Open();
                    SqlCommand com = con.CreateCommand();
                    if (IsNotRecord(com, ueEngine.Framework.Common.HashAlgorithm.Encrypt(item.Caption + ";" + item.ContactMan + ";" + item.ContactPhone, ueEngine.Framework.Common.EncryptMode.md5)))
                    {
                        int depositCompanyId = PostNewDepositCompany(com, agent, item.CompanyName, item.CopAbout, item.CopBusiness, item.CopType, item.CopDimensions);

                        int recruitId = PostNewRecruitSheet(com, item.Caption, agent, depositCompanyId, 1, item.ContactMan, item.ContactPhone, item.Address, ueEngine.Framework.Common.HashAlgorithm.Encrypt(
                            item.Caption + ";" + item.ContactMan + ";" + item.ContactPhone, ueEngine.Framework.Common.EncryptMode.md5));
                        PostNewPosition(com, recruitId, item.PositionName, item.Vacancy, item.PositionType, item.Salry, "不限", item.Degree, item.Experience, item.PositionDescript);
                        LogHelper.Write(CommonLogger.System, LogLevel.Info, "tran.Commit()");
                        con.Close();
                        return 1;
                    }
                    else
                    {
                        con.Close();
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.Write(CommonLogger.System, LogLevel.Error, e);
            }
            return 0;
        }
        private bool IsNotRecord(SqlCommand com, string querycode)
        {
            com.Parameters.Clear();
            com.CommandText = "select 1 from recruitsheet where querycode = @querycode";
            com.Parameters.Add(new SqlParameter("@querycode", querycode));
            object res = com.ExecuteScalar();
            return res == null;
        }
        private int PostNewDepositCompany(SqlCommand com, string agent, string companyName, string companyDetail, string bussiness, string copType, string copDim)
        {
            com.Parameters.Clear();
            com.CommandText = "insert into depositcompany(agent,companyname,companydetail,postdate,companybusiness,companytype,companydimensions,templete) values(@agent,@companyname,@companydetail,getdate(),@companybusiness,@companytype,@companydimensions,0) select SCOPE_IDENTITY()";
            com.CommandType = System.Data.CommandType.Text;
            com.Parameters.Add(new SqlParameter("@agent", agent));
            com.Parameters.Add(new SqlParameter("@companyname", companyName));
            com.Parameters.Add(new SqlParameter("@companydetail", companyDetail));
            com.Parameters.Add(new SqlParameter("@companybusiness", CompanyBusinessMapping(bussiness)));
            com.Parameters.Add(new SqlParameter("@companytype", CompanyTypeMapping(copType)));
            com.Parameters.Add(new SqlParameter("@companydimensions", CompanydimensionsMapping(copDim)));
            object res = com.ExecuteScalar();
            return Convert.ToInt32(res);
        }
        private int PostNewRecruitSheet(SqlCommand com, string caption, string agent, int depositionCompanyId, int recruitType, string Contact, string ContactPhone, string address, string querycode)
        {
            com.Parameters.Clear();
            com.CommandText = "insert into recruitsheet(caption,recruiter,depositcompanyId,recruitType,recruitSubject,contact,contactphone,workarea,workaddress,publishdate,customermanager,templete,isverify,enableemail,querycode,refresh,Source) values(@caption,@recruiter,@depositcompanyId,@recruitType,@recruitSubject,@contact,@contactphone,@workarea,@workaddress,getdate(),null,0,1,0,@querycode,getdate(),-1)select SCOPE_IDENTITY()";
            com.CommandType = System.Data.CommandType.Text;
            com.Parameters.Add(new SqlParameter("@caption", caption));
            com.Parameters.Add(new SqlParameter("@recruiter", agent));
            com.Parameters.Add(new SqlParameter("@depositcompanyId", depositionCompanyId));
            com.Parameters.Add(new SqlParameter("@recruitType", recruitType));
            if (new Random().Next(0, 100) < 5)
            {
                com.Parameters.Add(new SqlParameter("@recruitSubject", (object)1));
            }
            else
            {
                com.Parameters.Add(new SqlParameter("@recruitSubject", (object)0));
            }
            com.Parameters.Add(new SqlParameter("@contact", Contact));
            com.Parameters.Add(new SqlParameter("@contactphone", ContactPhone));
            com.Parameters.Add(new SqlParameter("@workarea", WorkAreaMapping(address)));
            com.Parameters.Add(new SqlParameter("@workaddress", address));
            com.Parameters.Add(new SqlParameter("@querycode", querycode));
            object res = com.ExecuteScalar();
            return Convert.ToInt32(res);
        }
        private void PostNewPosition(SqlCommand com, int recruitId, string positionName, string vacancy, int positionType, string salary, string gender, string degree, string experienced, string positionDesctipt)
        {
            com.Parameters.Clear();
            com.CommandText = "insert into position(recruitId,positionName,vacancy,positiontype,minsalary,maxsalary,period,gender,degree,experienced,positiondescript,scantime,operatorname,trusteeship,isindex,positionpriority,positionlevel) values(@recruitId,@positionName,@vacancy,@positiontype,@minsalary,@maxsalary,@period,@gender,@degree,@experienced,@positiondescript,0,'',0,0,0,0) select SCOPE_IDENTITY()";
            com.CommandType = System.Data.CommandType.Text;
            com.Parameters.Add(new SqlParameter("@recruitId", recruitId));
            com.Parameters.Add(new SqlParameter("@positionName", positionName));
            com.Parameters.Add(new SqlParameter("@vacancy", VacancyMapping(vacancy)));
            com.Parameters.Add(new SqlParameter("@positiontype", positionType));
            com.Parameters.Add(new SqlParameter("@minsalary", GetMinSalary(salary)));
            com.Parameters.Add(new SqlParameter("@maxsalary", GetMaxSalary(salary)));
            com.Parameters.Add(new SqlParameter("@period", GetSalaryPeriod(salary)));
            com.Parameters.Add(new SqlParameter("@gender", GenderMapping(gender)));
            com.Parameters.Add(new SqlParameter("@degree", DegreeMapping(degree)));
            com.Parameters.Add(new SqlParameter("@experienced", ExperiencedMapping(experienced)));
            com.Parameters.Add(new SqlParameter("@positiondescript", positionDesctipt.Replace("<br/>", "\r\n")));
            object res = com.ExecuteScalar();
        }
    }

    #region Common
    public static class Common
    {
        static int idx = 1;           //"51944179@qq.com", "214936150@qq.com", "1654625358@qq.com", "634691728@qq.com"
        static string[] recruiter = { "1768050400@qq.com", "1617047154@qq.com", "1274584051@qq.com" };
        public static string DoRequest(string url)
        {
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            request.UserAgent = "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            request.Accept = "*/*";
            request.KeepAlive = true;
            request.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");

            System.Net.HttpWebResponse response = null;
            response = (System.Net.HttpWebResponse)request.GetResponse();

            System.IO.Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            using (System.IO.StreamReader reader = new System.IO.StreamReader(dataStream, System.Text.Encoding.GetEncoding("utf-8")))
            {
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                responseFromServer = responseFromServer.Replace("\r", "").Replace("\n", "");
                return responseFromServer;
            }
        }
        public static DateTime ToDate(this string date)
        {
            DateTime dt = DateTime.Now;
            if (DateTime.TryParse(date, out dt))
            {
                return dt;
            }
            return DateTime.Now;
        }
        public static void RecordToDB(ref int count, List<Info> data)
        {
            using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=Sql1001.webweb.com,2433;Initial Catalog=DB_98EBF3_ueEngine;User ID=DB_98EBF3_ueEngine_admin;Password=ueEngine2012;Asynchronous Processing=true"))
            {
                con.Open();
                foreach (var item in data)
                {
                    try
                    {
                        System.Data.SqlClient.SqlCommand com = con.CreateCommand();
                        com.CommandText = String.Format("insert into SourceData values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}'," +
                        "'{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}')",
                        item.orgId, item.Caption, item.PublishDate.ToShortDateString(), item.ContactMan, item.ContactPhone, item.Area, item.Address,
                        item.PositionType, item.PositionName, item.Vacancy, item.Salry, item.Period, item.Experience, item.Degree, item.PositionDescript,
                        item.CompanyName, item.CopBusiness, item.CopType, item.CopAbout, item.CopDimensions);
                        com.CommandType = System.Data.CommandType.Text;
                        int affect = com.ExecuteNonQuery();
                        if (affect == 1)
                        {
                            Console.WriteLine("还剩" + --count + "条数据等待写入");
                        }
                        com.Dispose();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("写入第：" + --count + "数据时出现异常" + Environment.NewLine + e.Message);

                        using (System.IO.StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "writeToDbErr.txt"))
                        {
                            sw.WriteLine(e.ToString());
                        }
                    }
                }
            }
        }
        public static string GetRecruiter()
        {
            idx = idx == recruiter.Length ? 0 : idx + 1;
            return recruiter[idx % recruiter.Length];
        }
    }
    #endregion

    #region Data
    public class Info
    {
        public string orgId { get; set; }

        public string Caption { get; set; }
        public DateTime PublishDate { get; set; }
        public string ContactMan { get; set; }
        public string ContactPhone { get; set; }
        public int Area { get; set; }
        public string Address { get; set; }

        //职位
        public int PositionType { get; set; }
        public string PositionName { get; set; }
        public string Vacancy { get; set; }
        public string Salry { get; set; }
        public string Period { get; set; }
        public string Experience { get; set; }
        public string Degree { get; set; }
        public string PositionDescript { get; set; }

        //company
        public string CompanyName { get; set; }
        /// <summary>
        /// 公司行业
        /// </summary>
        public string CopBusiness { get; set; }
        /// <summary>
        /// 公司性质
        /// </summary>
        public string CopType { get; set; }
        /// <summary>
        /// 规模
        /// </summary>
        public string CopDimensions { get; set; }
        /// <summary>
        /// 公司简介
        /// </summary>
        public string CopAbout { get; set; }
    }
    public class PerpareData
    {
        public DateTime LastTime { get; set; }
    }
    #endregion
    public static class StringPlus
    {
        #region 删除最后一个字符之后的字符
        /// <summary>
        /// 删除最后结尾的指定字符后的字符
        /// </summary>
        public static string DelLastChar(this string str, string strchar)
        {
            return str.Substring(0, str.LastIndexOf(strchar));
        }

        #endregion
        /// <summary>
        /// 分裂字符串
        /// </summary>
        /// <param name="input">原字符串</param>
        /// <param name="splstr">分割标签</param>
        /// <param name="removeempty">是否去除空白段</param>
        /// <returns></returns>
        public static IEnumerable<string> SplitString(this string input, char splstr, bool removeempty)
        {
            if (!String.IsNullOrEmpty(input))
            {
                return input.Split(splstr).Where(c =>
                {
                    if (removeempty)
                    {
                        if (!String.IsNullOrEmpty(c))
                        {
                            return true;
                        }
                        return false;
                    }
                    return true;
                });

            }
            return null;
        }

        /// <summary>
        /// 转全角的函数(SBC case)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToSBC(this string input)
        {
            //半角转全角：
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }

        /// <summary>
        ///  转半角的函数(SBC case)
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        public static string ToDBC(this string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }

        #region 去除字符串中的所有网页标签
        /// <summary>
        /// 去除字符串中的所有网页标签
        /// </summary>
        /// <param name="str">需要处理的字符串</param>
        /// <returns></returns>
        public static string NoHTMLLabel(this string str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return str;
            }
            Regex regex = new Regex("</?.*?>", RegexOptions.IgnoreCase);
            string s = regex.Replace(str, "");
            string s1 = s.Replace("\n", "").Replace("\r", "").Trim();
            return s1;
        }
        public static string EmptyHTMLLabel(this string str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return str;
            }
            //Regex regex = new Regex("<(.*)?>.*?</\\1>", RegexOptions.IgnoreCase);
            Regex regex = new Regex("<(\\w+)\\s+.*?>.*?</\\1>", RegexOptions.IgnoreCase);
            string s = regex.Replace(str, "");
            string s1 = s.Replace("\n", "").Replace("\r", "").Trim();
            return s1;
        }
        /// <summary>
        /// 替换掉特定标签
        /// </summary>
        /// <param name="str"></param>
        /// <param name="labelName"></param>
        /// <returns></returns>
        public static string NoHTMLLabel(this string str, string labelName)
        {
            if (String.IsNullOrEmpty(str))
            {
                return str;
            }
            Regex regex = new Regex("</?" + labelName + ".*?>", RegexOptions.IgnoreCase);
            return regex.Replace(str, "");
        }
        /// <summary>
        /// 删除html标记。并返回指定长度的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="charLength"></param>
        /// <returns></returns>
        public static string NoHTMLLabel(this string str, int charLength)
        {
            string result = str.NoHTMLLabel();
            if (result.Length <= charLength)
                return result;
            return result.Substring(0, charLength);
        }
        #endregion
        /// <summary>
        /// 删除空白
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string NoSpace(this string str)
        {
            return str.Replace(" ", "");
        }
        /// <summary>
        /// 截取字符串中的一段
        /// </summary>
        /// <param name="source"></param>
        /// <param name="startIndex"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string PieceOfString(this string source, int startIndex, int length)
        {
            if (source.Length < startIndex)
            {
                return String.Empty;
            }
            if (source.Length < startIndex + length)
            {
                return source.Substring(startIndex);
            }
            return source.Substring(startIndex, length);
        }
        /// <summary>
        /// 查看字符串中是否包含某些字符
        /// </summary>
        /// <param name="str">目标字符串</param>
        /// <param name="regexp">匹配正则表达式</param>
        /// <returns></returns>
        public static bool Contains(this string str, string regexp, RegexOptions option)
        {
            Regex reg = new Regex(regexp, option);
            return reg.IsMatch(str);
        }
    }
}
